package com.winning.devops.batch.processor.ch01.config;

import com.winning.devops.batch.processor.ch01.domain.Customer;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.CompositeItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/**
 * Processor数据处理Job配置
 *
 * @author chensj
 * @date 2020-03-07 21:20
 */
@Configuration
public class ProcessorDemoJobConfig {


    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private StepBuilderFactory stepBuilderFactory;
    @Autowired
    @Qualifier("processorFileItemDemoReader")
    private ItemReader<? extends Customer> processorFileItemDemoReader;
    @Autowired
    @Qualifier("processorFlatFileDemoWriter")
    public ItemWriter<? super Customer> processorFlatFileDemoWriter;
    @Autowired
    @Qualifier("firstNameItemProcessor")
    private ItemProcessor<? super Customer, ? extends Customer> firstNameItemProcessor;
    @Autowired
    @Qualifier("idFilterItemProcessor")
    private ItemProcessor<? super Customer, ? extends Customer> idFilterItemProcessor;


    @Bean
    public Job processorDemoJob() {
        return jobBuilderFactory.get("processorDemoJob")
                .start(processorDemoStep())
                .build();
    }

    @Bean
    public Step processorDemoStep() {
        return stepBuilderFactory.get("processorDemoStep")
                .<Customer, Customer>chunk(10)
                .reader(processorFileItemDemoReader)
                .processor(firstNameItemProcessor)
                .writer(processorFlatFileDemoWriter)
                .build();
    }

    /**
     * 多种数据处理方式
     * <p>
     * 通过CompositeItemProcessor来指定代理类
     *
     * @return ItemProcessor
     */
    @Bean
    public CompositeItemProcessor<Customer, Customer> customerCompositeItemProcessor() throws Exception {
        CompositeItemProcessor<Customer, Customer> processor = new CompositeItemProcessor<>();
        processor.setDelegates(Arrays.asList(firstNameItemProcessor, idFilterItemProcessor));
        processor.afterPropertiesSet();
        return processor;
    }


}
